<?php

/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 23.03.14
 * Time: 1:09
 */

include_once BASE_DQ_PLUGIN_PATH . "classes/QuestionDao.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/AnswerDao.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/ResultDao.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/QuizResult.php";

class QuizResultChecker
{
    /**
     * @param int $quizId
     * @param int $studentId
     * @return QuizResult
     */
    public function check($quizId, $studentId)
    {
        $questionDao = new QuestionDao();
        $answerDao = new AnswerDao();
        $resultDao = new ResultDao();

        $questions = $questionDao->getAllByQuizId($quizId);

        $quizResult = new QuizResult();
        $quizResult->maxScore = count($questions);

        $results = $resultDao->getAllByQuizUser($quizId, $studentId);
        if (count($results) == 0) {
            return null;
        }

        foreach ($questions as $question) {
            $question->answers = $answerDao->getAllByQuestionId($question->id);

            $result = $resultDao->getByQuizQuestionUser(
                $quizId,
                $question->id,
                $studentId
            );
            $totalCorrectAnsCount = $question->getCorrectAnswersCount();

            $currCorrectAnsCount = 0;
            foreach ($question->answers as $answer) {
                if ($answer->isCorrect
                    && $result
                    && in_array($answer->id, $result->answers)
                ) {
                    $currCorrectAnsCount++;
                }

                if (!$answer->isCorrect
                    && $result
                    && in_array($answer->id, $result->answers)
                ) {
                    $currCorrectAnsCount=0;
                    break;
                }
            }
            $currCorrectAnsCount = ($currCorrectAnsCount > 0) ? $currCorrectAnsCount : 0;

            if ($currCorrectAnsCount == $totalCorrectAnsCount) {
                $quizResult->finishedQuestions[] = $question->id;
            }

            $quizResult->score += floatval(
                sprintf("%.2f", ($currCorrectAnsCount / $totalCorrectAnsCount))
            );
        }

        return $quizResult;
    }
}